<template>
  <!-- 联系人列表 -->
  <div class="contact-list">
    <!-- navbar标题栏 -->
    <van-nav-bar title="联系人列表" left-text="返回" left-arrow @click-left="goBack" />
    <!-- 列表 -->
    <van-contact-list
      v-model="chosenContactId"
      :list="list"
      @add="onAdd"
      @edit="onEdit"
      @select="onSelect"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      chosenContactId: "1",
      list: []
    };
  },
  mounted() {
    this.loadContactList();
  },
  methods: {
    /**
     * 获取联系人列表信息
     */
    loadContactList() {
      this.http
        .get(this.$api.getContactAll)
        .then(res => res.data)
        .then(res => {
          if (res?.code == 200) {
            this.list = res?.data;

            // 遍历修改isDefault的值
            this.list.forEach(item => {
              if (item.isDefault == 1) {
                // 设置默认选中
                this.chosenContactId = item.id;
              }
            });
          }
        });
    },

    /**
     * 返回至上一页
     */
    goBack() {
      this.$router.back();
    },
    onAdd() {
      this.$router.push("/contactAdd");
    },
    onEdit(contact) {
      this.$router.push(`/contactEdit/${contact.id}`);
    },
    onSelect(contact) {
      //this.$msg.fail("选择" + contact.id);
      // 设置默认联系人
      this.http
        .put(`${this.$api.setContact}/${contact.id}`)
        .then(res => res.data)
        .then(res => {
          if (res?.code == 200) {
            this.$msg.success(res?.msg);
            this.chosenContactId = contact.id;
          } else {
            this.$msg.fail(res?.msg);
          }
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.van-button--danger {
  color: #fff;
  background-color: #f8e176;
  border: 1px solid #f8e176;
}
</style>